﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Linq;
using System.Data.OracleClient;
using System.Data;
using Microsoft.SharePoint.WebControls;
using SP_XHWeb.BPMService;
using System.ServiceModel;
using SP_XHWeb.TaskWake;

namespace SP_XHWeb.ControlTemplates.SP_XHWeb
{
    public partial class TopStudy : UserControl
    {
        private string DispFormUrl = "/_layouts/SP_XHWeb/DispFormItem.aspx?1=1";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {                
                lblStudy.InnerHtml = InitTopStudy();
                lbloffice.InnerHtml = InitTopOffice();
            }
        }

        private string InitTopStudy()
        {
            StringBuilder str = new StringBuilder();
            List<SPListItem> groupLists = GetGroupTopStudy();
            //List<SPListItem> projectLists = GetProjectTopStudy();
            //标题长度
            int len = 18;

            str.Append("<ul>");

            if (groupLists != null && groupLists.Count > 6)
            {
                groupLists = (from emp in groupLists orderby emp["创建时间"] descending select emp).Take(6).ToList<SPListItem>();
                for (int i = 0; i < 6; i++)
                {
                    string[] strs = groupLists[i]["Categories"].ToString().Split('_');
                    string linkUrl = "";
                    string fileUrl = "";
                    if (groupLists[i]["Content"] != null && !string.IsNullOrEmpty(groupLists[i]["Content"].ToString()))
                    {
                        string tempUrl = groupLists[i]["Content"].ToString().Substring(groupLists[i]["Content"].ToString().IndexOf('@') + 1);
                        fileUrl = tempUrl.Substring(0, tempUrl.LastIndexOf('@'));
                    }

                    if (strs.Length == 3)
                    {
                        linkUrl = "/" + strs[0] + "/" + strs[1] + "/" + (!string.IsNullOrEmpty(fileUrl) ? fileUrl : strs[2] + "/" + groupLists[i].Title);
                    }
                    else if (strs.Length == 2)
                    {
                        linkUrl = "/" + strs[0] + "/" + (!string.IsNullOrEmpty(fileUrl) ? fileUrl : strs[1] + "/" + groupLists[i].Title);
                    }
                    str.Append("<li>");
                    if (groupLists[i].Title.Length > len)
                    {
                        str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, groupLists[i].Title.Substring(0, len) + "...");
                    }
                    else
                    {
                        str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, groupLists[i].Title);
                    }
                    str.Append("</li>");
                }
            }
            else
            {
                groupLists = (from emp in groupLists orderby emp["创建时间"] descending select emp).ToList<SPListItem>();
                for (int i = 0; i < groupLists.Count; i++)
                {
                    string[] strs = groupLists[i]["Categories"].ToString().Split('_');
                    string linkUrl = "";
                    string fileUrl = "";
                    if (groupLists[i]["Content"] != null && !string.IsNullOrEmpty(groupLists[i]["Content"].ToString()))
                    {
                        string tempUrl = groupLists[i]["Content"].ToString().Substring(groupLists[i]["Content"].ToString().IndexOf('@') + 1);
                        fileUrl = tempUrl.Substring(0, tempUrl.LastIndexOf('@'));
                    }

                    if (strs.Length == 3)
                    {
                        linkUrl = "/" + strs[0] + "/" + strs[1] + "/" + (!string.IsNullOrEmpty(fileUrl) ? fileUrl : strs[2] + "/" + groupLists[i].Title);
                    }
                    else if (strs.Length == 2)
                    {
                        linkUrl = "/" + strs[0] + "/" + (!string.IsNullOrEmpty(fileUrl) ? fileUrl : strs[1] + "/" + groupLists[i].Title);
                    }
                    str.Append("<li>");
                    if (groupLists[i].Title.Length > len)
                    {
                        str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, groupLists[i].Title.Substring(0, len) + "...");
                    }
                    else
                    {
                        str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, groupLists[i].Title);
                    }
                    str.Append("</li>");
                }
            }



            #region 子站点知识中心
            //if (projectLists != null && projectLists.Count > 3)
            //{
            //    for (int i = 0; i < 3; i++)
            //    {
            //        string[] strs = projectLists[i]["Categories"].ToString().Split('_');
            //        string[] strcs = projectLists[i]["分类"].ToString().Split('_');
            //        string linkUrl = "";
            //        if (strs.Length == 3)
            //        {
            //            linkUrl = DispFormUrl + "&web_url=/" + strs[0] + "/" + strs[1] + "&list_title=" + strs[2] + "&item_id=" + projectLists[i]["SID"];
            //        }
            //        else if (strs.Length == 2)
            //        {
            //            linkUrl = DispFormUrl + "&web_url=/" + strs[0] + "&list_title=" + strs[1] + "&item_id=" + projectLists[i]["SID"];
            //        } 
            //        str.Append("<li>");
            //        if (projectLists[i].Title.Length > len)
            //        {
            //            str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, "【" + strcs[1].Replace("项目", "") + "】" + projectLists[i].Title.Substring(0, len) + "...");
            //        }
            //        else
            //        {
            //            str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, "【" + strcs[1].Replace("项目", "") + "】" + projectLists[i].Title);
            //        }
            //        str.Append("</li>");
            //    }
            //}
            //else
            //{
            //    for (int i = 0; i < projectLists.Count; i++)
            //    {
            //        string[] strs = projectLists[i]["Categories"].ToString().Split('_');
            //        string[] strcs = projectLists[i]["分类"].ToString().Split('_');
            //        string linkUrl = "";
            //        if (strs.Length == 3)
            //        {
            //            linkUrl = DispFormUrl + "&web_url=/" + strs[0] + "/" + strs[1] + "&list_title=" + strs[2] + "&item_id=" + projectLists[i]["SID"];
            //        }
            //        else if (strs.Length == 2)
            //        {
            //            linkUrl = DispFormUrl + "&web_url=/" + strs[0] + "&list_title=" + strs[1] + "&item_id=" + projectLists[i]["SID"];
            //        } 
            //        str.Append("<li>");
            //        if (projectLists[i].Title.Length > len)
            //        {
            //            str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, "【" + strcs[1].Replace("项目", "") + "】" + projectLists[i].Title.Substring(0, len) + "...");
            //        }
            //        else
            //        {
            //            str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", linkUrl, "【" + strcs[1].Replace("项目", "") + "】" + projectLists[i].Title);
            //        }
            //        str.Append("</li>");
            //    }
            //}
            #endregion

            str.Append("</ul>");
            return str.ToString();
        }


        //资讯中心需要显示的信息
        private List<SPListItem> GetGroupTopStudy()
        {
            List<SPListItem> lists = new List<SPListItem>();
            //  http://
            string listUrl = this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority;
            using (SPSite site = new SPSite(listUrl + "/approveknowledge"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("ShowShareList");
                    if (list != null && list.ItemCount != 0)
                    {
                        foreach (SPListItem item in list.Items)
                        {
                            if (item.Fields.ContainsField("是否显示"))
                            {
                                if (item["是否显示"] != null && !string.IsNullOrEmpty(item["是否显示"].ToString()) && item["是否显示"].ToString() == "显示" && item["Categories"].ToString().Contains("KnowledgeShare"))
                                {
                                    lists.Add(item);
                                }
                            }
                        }
                    }
                }
            }
            //using (SPSite site = new SPSite(listUrl + "/infomationcenter/default.aspx"))
            //{
            //    using (SPWeb web = site.OpenWeb())
            //    {
            //        SPList list = web.Lists.TryGetList("InfomationStudy");
            //        if (list != null && list.ItemCount != 0)
            //        {
            //            foreach (SPListItem item in list.Items)
            //            {
            //                if (item.Fields.ContainsField("首页显示"))
            //                {
            //                    if (item["首页显示"] != null && !string.IsNullOrEmpty(item["首页显示"].ToString()) && item["首页显示"].ToString() == "显示")
            //                    {
            //                        lists.Add(item);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            return lists;
        }

        //项目信息需要显示的信息
        //private List<SPListItem> GetProjectTopStudy()
        //{
        //    List<SPListItem> lists = new List<SPListItem>();
        //    //  http://
        //    string listUrl = this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority;
        //    using (SPSite site = new SPSite(listUrl + "/default.aspx"))
        //    {
        //        using (SPWeb web = site.OpenWeb())
        //        {
        //            SPList list = web.Lists.TryGetList("ShowShareList");
        //            if (list != null && list.ItemCount != 0)
        //            {
        //                foreach (SPListItem item in list.Items)
        //                {
        //                    if (item.Fields.ContainsField("是否显示"))
        //                    {
        //                        if (item["是否显示"] != null && !string.IsNullOrEmpty(item["是否显示"].ToString()) && item["是否显示"].ToString() == "显示" && item["Categories"].ToString().Contains("ProjectStudy"))
        //                        {
        //                            lists.Add(item);
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //using (SPSite site = new SPSite(listUrl + "/projectinfo/default.aspx"))
        //{
        //    using (SPWeb pweb = site.OpenWeb())
        //    {
        //        //子站点
        //        if (pweb.Webs.Count != 0)
        //        {
        //            foreach (SPWeb web in pweb.Webs)
        //            {
        //                SPList list = web.Lists.TryGetList("ProjectStudy");
        //                if (list != null && list.ItemCount != 0)
        //                {
        //                    foreach (SPListItem item in list.Items)
        //                    {
        //                        if (item.Fields.ContainsField("首页显示"))
        //                        {
        //                            if (item["首页显示"] != null && !string.IsNullOrEmpty(item["首页显示"].ToString()) && item["首页显示"].ToString() == "显示")
        //                            {
        //                                lists.Add(item);
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}
        //return lists;
        //}



        public string GetCount()
        {
            string count = "0";
            string OracleConnectionString = @"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.3.9.14)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=oradb)));User ID=kd;Password=kd;Unicode=True";
            string OracleSelectString = "select count(*) from eas.ct_view_workflow";
            string username = string.Empty;
            try
            {
                string tempname = SPControl.GetContextWeb(this.Context).CurrentUser.LoginName;
                username = tempname.Contains("\\") ? tempname.Substring(tempname.IndexOf("\\") + 1) : tempname;
                using (OracleConnection connection = new OracleConnection(OracleConnectionString))
                {
                    OracleCommand command = connection.CreateCommand();
                    if (!string.IsNullOrEmpty(username))
                    {
                        command.CommandText = OracleSelectString + " where receiver='" + username + "'";
                    }
                    else
                    {
                        string tempname2 = SPContext.Current.Web.CurrentUser.LoginName;
                        username = tempname2.Contains("\\") ? tempname2.Substring(tempname2.IndexOf("\\") + 1) : tempname2;
                        command.CommandText = OracleSelectString + " where receiver='" + username + "'";
                    }
                    connection.Open();
                    OracleDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        count = reader[0].ToString();
                    }
                    reader.Close();
                }
            }
            catch
            {
                count = "0";
            }

            return count;
        }

        public string GetUserName()
        {
            string tempname = SPControl.GetContextWeb(this.Context).CurrentUser.LoginName;
            string username = tempname.Contains("\\") ? tempname.Substring(tempname.IndexOf("\\") + 1) : tempname;
            return username;
        }

        private string InitTopOffice()
        {
            // TaskWake.TaskWakeServiceSoapClient client = new TaskWake.TaskWakeServiceSoapClient();
            
            StringBuilder str = new StringBuilder();
            try
            {
                List<SPListItem> lists = GetLinks("RootFolder");
                string moreLinkStr = "更多业务系统";
                List<SPListItem> moreLinks = GetLinks(moreLinkStr);
                str.Append("<ul>");
                string namestr = GetUserName();
                string userCode = "xh_" + namestr;
                if (lists != null && lists.Count != 0)
                {
                    if (lists.Count > 10)
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            str.Append("<li>");
                            str.AppendFormat(lists[i]["Picture"].ToString());
                            if (lists[i].Title.Trim().StartsWith("OA") && !string.IsNullOrEmpty(namestr))
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}<iframe id='iframeNum' src='{2}' name='iframeNum' frameborder='0' scrolling='no'></iframe></a>", lists[i]["LinkUrl"], lists[i].Title, "http://10.3.9.18:89?username=" + namestr);
                            }
                            else if (lists[i].Title.Equals("新流程待办") && !string.IsNullOrEmpty(namestr))
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}({2})</a>", lists[i]["LinkUrl"], lists[i].Title, this.GetBPMUnfinishedWorkItemCount(namestr));
                            }
                            else if (lists[i].Title.Equals("采招系统待办") && !string.IsNullOrEmpty(namestr))
                            {
                                // TBD
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}({2})</a>", lists[i]["LinkUrl"] + "?usercode=" + userCode, lists[i].Title, this.GetTaskWakeWorkItemCount(namestr));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i]["LinkUrl"], lists[i].Title);
                            }
                            str.Append("</li>");
                        }
                    }

                    else
                    {
                        for (int i = 0; i < lists.Count; i++)
                        {
                            str.Append("<li>");
                            str.AppendFormat(lists[i]["Picture"].ToString());

                            if (lists[i].Title.Trim().StartsWith("OA") && !string.IsNullOrEmpty(namestr))
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}<iframe id='iframeNum' src='{2}' name='iframeNum' frameborder='0' scrolling='no'></iframe></a>", lists[i]["LinkUrl"], lists[i].Title, "http://10.3.9.18:89?username=" + namestr);
                            }
                            else if (lists[i].Title.Trim().Equals("新流程待办") && !string.IsNullOrEmpty(namestr))
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}({2})</a>", lists[i]["LinkUrl"], lists[i].Title, this.GetBPMUnfinishedWorkItemCount(namestr));
                            }
                            else if (lists[i].Title.Equals("采招系统待办") && !string.IsNullOrEmpty(namestr))
                            {
                                // TBD
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}({2})</a>", lists[i]["LinkUrl"] + "?usercode=" + userCode, lists[i].Title, this.GetTaskWakeWorkItemCount(namestr));
                            }
                            else
                            {
                                str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i]["LinkUrl"], lists[i].Title);
                            }
                            str.Append("</li>");
                        }
                    }
                }

                if (moreLinks.Count > 0)
                {
                    str.Append("<li class='flyoutParent'>");
                    //str.AppendFormat("<div class='ExternalClassFB23D9E7FB3841178B015A0D9F995F42'><img width='33' height='26' src='/_layouts/images/SP_XHWeb/System.png' alt=''/></div>");
                    str.AppendFormat("<img width='13' id='moreLinksRowNumberExpand' height='13' src='/_layouts/images/SP_XHWeb/expand.png' alt=''/>");
                    str.AppendFormat("<img width='13' id='moreLinksRowNumberCollpase' height='13' src='/_layouts/images/SP_XHWeb/collpase.png' class='hiddenImg' alt=''/>");
                    str.Append("<div class='flyout'>");
                    str.AppendFormat("<ul>");
                    foreach (var link in moreLinks)
                    {
                        str.AppendFormat("<li>");
                        str.AppendFormat(link["Picture"].ToString());
                        str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", link["LinkUrl"], link.Title);
                        str.AppendFormat("</li>");
                    }
                    str.AppendFormat("</ul>");
                    str.Append("</div>");
                    //    str.AppendFormat("<a href='{0}' target='_blank'>{1}</a>", lists[i]["LinkUrl"], lists[i].Title);
                    str.AppendFormat(moreLinkStr);

                    str.Append("</li>");

                }

                str.Append("</ul>");
                // <input type='hidden' name='moreLinksRowNumber' value='2' id='moreLinksRowNumber' />
                str.AppendFormat("<input type='hidden' name='moreLinksRowNumber' value='{0}' id='moreLinksRowNumber' />", (moreLinks.Count + 1) / 2);
            }
            catch (Exception ex)
            {
                str.AppendLine("Error:"+ ex.Message);
                str.AppendLine("Error stackTrace:" + ex.StackTrace);
                str.AppendLine("Error Source:" + ex.Source);
            }

            return str.ToString();
        }

        private string GetTaskWakeWorkItemCount(string alias)
        {
            TaskWakeServiceSoapClient client = Helper.GetTaskWakeServiceSoapClient();
            string josnResult = client.GetMyTaskWake("xh_" + alias);
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            TaskWakeData data = jsonSerializer.Deserialize<TaskWakeData>(josnResult);

            string count = "0";
            if (data.Data != null)
            {
                count = data.Data.Length.ToString();
            }

            return count;

        }

        // 取BPM平台待办数量
        private string GetBPMUnfinishedWorkItemCount(string alias)
        {
            int count = 0;
            try
            {
                BPMServiceSoapClient BPMServiceClient = this.GetBPMServiceClient();
                count = BPMServiceClient.GetUserUnfinishedWorkItemCount(alias);
            }
            catch (Exception ex)
            {
                return "<font color=red>" + count + "</font>";
            }

            return  count.ToString();
        }

        // 构造BPM web service客户端
        private BPMServiceSoapClient GetBPMServiceClient()
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            // I think most (or all) of these are defaults--I just copied them from app.config:
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;
            return new BPMServiceSoapClient(binding, new EndpointAddress("http://bpm.starcapital.com.cn:8010/Portal/WebServices/BPMService.asmx"));
        }


        //项目信息需要显示的信息
        private List<SPListItem> GetLinks(string folderName)
        {
            List<SPListItem> lists = new List<SPListItem>();
            //  http://
            string listUrl = this.Page.Request.Url.Scheme + "://" + this.Page.Request.Url.Authority;
            using (SPSite site = new SPSite(listUrl + "/default.aspx"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("PersonalOffice");
                    if (list != null && list.ItemCount != 0)
                    {
                        SPQuery query = new SPQuery();
                        SPFolder folder = null;
                        if (folderName.Equals("RootFolder"))
                        {
                            folder = list.RootFolder;
                        }
                        else
                        {
                            foreach (SPListItem currentFolder in list.Folders)
                            {
                                if (currentFolder["Title"].ToString().Equals(folderName))
                                {
                                    folder = currentFolder.Folder;
                                    break;
                                }
                            }
                        }

                        query.Folder = folder;                     
                        foreach (SPListItem item in list.GetItems(query))
                        {
                            if (item.Fields.ContainsField("LinkUrl"))
                            {
                                if (item["LinkUrl"] != null && !string.IsNullOrEmpty(item["LinkUrl"].ToString()))
                                {
                                    lists.Add(item);
                                }
                            }
                        }
                    }

                    if (list.Fields.ContainsFieldWithStaticName("Order0"))
                    {
                             lists.Sort((x, y) => {
                            int xOrder = int.Parse(x["Order0"].ToString());
                            int yOrder = int.Parse(y["Order0"].ToString());
                            return xOrder - yOrder;                 
                       });
                    }
                }               

            }            

            return lists;
        }

        private List<SPListItem> GetMoreLinks()
        {
            List<SPListItem> lists = new List<SPListItem>();

            return lists;
        }
    }
}
